package com.oracle.outsidein.pool;

import com.oracle.outsidein.OutsideinManagerConfig;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ProcessManager {
    private final OutsideinManagerConfig config;
    private ExecutorService executorService;

    public ProcessManager(OutsideinManagerConfig config) {
        this.config = config;
    }

    public void startup() {
        this.executorService = Executors.newFixedThreadPool(config.getTaskSize(), new NamedThreadFactory("outsidein-task"));
    }

    public void shutdown() {
        this.executorService.shutdown();
    }

    public boolean isRun() {
        return !executorService.isShutdown();
    }

    public Future<ConvertResult> execute(ConvertTaskInfo info) {
        // 根据文件类型自动判断使用的工具
        if (info.getOitType() == null) {
            String name = info.getDstFile().toLowerCase();
            if (name.endsWith(".html")) {
                info.setOitType(OitType.wv);
            } else if (name.endsWith(".pdf")) {
                info.setOitType(OitType.px);
            } else {
                info.setOitType(OitType.ix);
            }
        }
        // 根据类型创建任务
        AbstractConvertTask convertTask;
        switch (info.getOitType()) {
            case wv:
                convertTask = new ConvertTaskWv(info);
                break;
            case px:
                convertTask = new ConvertTaskPx(info);
                break;
            case ix:
                convertTask = new ConvertTaskIx(info);
                break;
            default:
                throw new IllegalStateException("Unexpected OitType value: " + info.getOitType());
        }
        convertTask.setConfig(config);
        return this.executorService.submit(convertTask);
    }
}
